import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Bar, Pie, Line, Grid, Page


# 读取统计数据
refund_reason_stats = pd.read_csv("refund_reason_stats.csv")
category_refund_stats = pd.read_csv("category_refund_stats.csv")
dayly_refund_trend = pd.read_csv("dayly_refund_trend.csv")

# 1. 退款原因分布饼图
pie = (
    Pie()
    .add(
        "退款原因",
        [list(z) for z in zip(refund_reason_stats["refund_reason"], refund_reason_stats["refund_count"])],
        radius=["30%", "75%"],
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(title="退款原因分布"),
        legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"),
        toolbox_opts=opts.ToolboxOpts(is_show=True)
    )
    .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)"))
)

# 2. 产品类别退款率柱状图
bar = (
    Bar()
    .add_xaxis(category_refund_stats["product_category"].tolist())
    .add_yaxis("退款率(%)", category_refund_stats["refund_rate"].round(2).tolist(), color="#5793f3")
    .set_global_opts(
        title_opts=opts.TitleOpts(title="各产品类别退款率"),
        toolbox_opts=opts.ToolboxOpts(is_show=True),
        xaxis_opts=opts.AxisOpts(axislabel_opts={"rotate": 45}),
        yaxis_opts=opts.AxisOpts(name="退款率(%)")
    )
    .set_series_opts(label_opts=opts.LabelOpts(position="top"))
)

# 3. 月度退款趋势图
line1 = (
    Line()
    .add_xaxis(dayly_refund_trend["refund_day"].tolist())
    .add_yaxis(
        "退款数量",
        dayly_refund_trend["refund_count"].tolist(),
        yaxis_index=0,
        color="#d14a61",
        label_opts=opts.LabelOpts(is_show=False)
    )
    .extend_axis(
        yaxis=opts.AxisOpts(
            name="退款金额",
            type_="value",
            min_=0,
            max_=dayly_refund_trend["refund_amount"].max() * 1.1,
            interval=dayly_refund_trend["refund_amount"].max() / 5,
            axislabel_opts=opts.LabelOpts(formatter="{value} 元")
        )
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(title="月度退款趋势"),
        tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"),
        yaxis_opts=opts.AxisOpts(
            name="退款数量",
            type_="value",
            min_=0,
            max_=dayly_refund_trend["refund_count"].max() * 1.1,
            interval=dayly_refund_trend["refund_count"].max() / 5,
            axislabel_opts=opts.LabelOpts(formatter="{value} 笔")
        ),
        toolbox_opts=opts.ToolboxOpts(is_show=True)
    )
)

line2 = (
    Line()
    .add_xaxis(dayly_refund_trend["refund_day"].tolist())
    .add_yaxis(
        "退款金额",
        dayly_refund_trend["refund_amount"].round(2).tolist(),
        yaxis_index=1,
        color="#675bba",
        label_opts=opts.LabelOpts(is_show=False)
    )
)

line = line1.overlap(line2)

# 创建页面组合图表
page = Page(layout=Page.DraggablePageLayout)
page.add(pie, bar, line)
page.render("refund_analysis_dashboard.html")

print("可视化页面已生成: refund_analysis_dashboard.html")